﻿using Sirius.Application;
using System.Net.WebSockets;
using System.Text.Json;
using static Sirius.Log.Log;
using static Sirius.Utils.Util;
using static Sirius.WebSocket.SiriusWebSocketBase;
using static Sirius.WebSocket.SiriusWebSocketClient;
using static Sirius.Data.PackManager;
using Sirius.SystemDll;

namespace Sirius.WebSocket.MessageManager
{

    public static class MessagePush
    {
        public static string BotId;
        public static string Token;
        public static int heartbeat_interval = 0;//心跳间隔

        public static string? session_id = null;//
        public static string? seq = "0";//理论上是消息顺序
        public static async void Message(Object sender, string message)
        {
            try
            {
                //将sender转换为SiriusClient
                ClientWebSocket SiriusClient = sender as ClientWebSocket;
                if (message == "")
                    return;
                var json = JsonDocument.Parse(message);
                int op = json.RootElement.GetProperty("op").GetInt32();
                switch (op)
                {
                    case 0://服务端进行消息推送
                        s += 1;
                        var pushData = json.RootElement.GetProperty("t").ToString();
                        switch (pushData)
                        {
                            case "READY"://鉴权成功，可以发送心跳包了
                                session_id = json.RootElement.GetProperty("d").GetProperty("session_id").ToString();
                                ApplicationManager.BotInfoPushForApplication(json.RootElement.GetProperty("d").GetProperty("user").ToString());
                                Sirius.Utils.Util.HeartBeat_Data = "";
                                //心跳时钟初始化
                                Sirius.Utils.Util.HeartartBeat_Timer.AutoReset = true;
                                Sirius.Utils.Util.HeartartBeat_Timer.Elapsed += new System.Timers.ElapsedEventHandler(Sirius.Utils.Util.send_HeartBeatPack);
                                Sirius.Utils.Util.HeartartBeat_Timer.Start();
                                LogSuc("Auth_Success", json.RootElement.GetProperty("d").GetProperty("user").GetProperty("username").GetString() + "登陆成功!");
                                break;
                            //--------------------------频道事件------------------------------
                            case "GUILD_CREATE"://机器人被加入到某个频道的时候
                                Task.Run(async () =>
                                {
                                    ApplicationManager.Guild_eventPushForApplication("GUILD_CREATE", message);
                                });
                                break;

                            case "GUILD_UPDATE"://频道信息变更
                                Task.Run(async () =>
                                {
                                    ApplicationManager.Guild_eventPushForApplication("GUILD_UPDATE", message);
                                });
                                break;

                            case "GUILD_DELETE"://频道被解散，或者当前机器人被移除
                                Task.Run(async () =>
                                {
                                    ApplicationManager.Guild_eventPushForApplication("GUILD_DELETE", message);
                                });
                                break;

                            //--------------------------子频道事件------------------------------
                            case "CHANNEL_CREATE"://子频道被创建
                                Task.Run(async () =>
                                {
                                    ApplicationManager.Channel_eventPushForApplication("CHANNEL_CREATE", message);
                                });
                                break;

                            case "CHANNEL_UPDATE"://子频道信息变更
                                Task.Run(async () =>
                                {
                                    ApplicationManager.Channel_eventPushForApplication("CHANNEL_UPDATE", message);
                                });
                                break;

                            case "CHANNEL_DELETE"://子频道被删除
                                Task.Run(async () =>
                                {
                                    ApplicationManager.Channel_eventPushForApplication("CHANNEL_DELETE", message);
                                });
                                break;

                            //--------------------------频道成员事件------------------------------
                            case "GUILD_MEMBER_ADD"://新用户加入频道
                                Task.Run(async () =>
                                {
                                    ApplicationManager.GuildMemberPushForApplication("GUILD_MEMBER_ADD", message);
                                });
                                break;

                            case "GUILD_MEMBER_UPDATE"://用户的频道属性发生变化，如频道昵称，或者身份组
                                Task.Run(async () =>
                                {
                                    ApplicationManager.GuildMemberPushForApplication("GUILD_MEMBER_UPDATE", message);
                                });
                                break;
                            case "GUILD_MEMBER_REMOVE"://用户离开频道
                                Task.Run(async () =>
                                {
                                    ApplicationManager.GuildMemberPushForApplication("GUILD_MEMBER_REMOVE", message);
                                });
                                break;

                            // 消息事件，仅 *私域* 机器人能够设置此 intents。
                            case "MESSAGE_CREATE":// 发送消息事件，代表频道内的全部消息，而不只是 at 机器人的消息。内容与 AT_MESSAGE_CREATE 相同
                                Console.WriteLine(message);
                                Task.Run(async () =>
                                {
                                    ApplicationManager.PrivateMessagePushForApplication("MESSAGE_CREATE", message);
                                    foreach (var socket in WebSocket.WebSocketAPI.WebSocketServerAPI.clientList)
                                    {
                                        socket.Send(message);
                                    }
                                });
                                break;
                            case "MESSAGE_DELETE":// 删除（撤回）消息事件
                                Task.Run(async () =>
                                {
                                    ApplicationManager. PrivateMessagePushForApplication("MESSAGE_DELETE", message);

                                });
                                break;
                            //--------------------------消息事件------------------------------
                            case "AT_MESSAGE_CREATE"://用户发送消息，@当前机器人或回复机器人消息时
                                seq = json.RootElement.GetProperty("d").GetProperty("seq").ToString();
                                Task.Run(async () =>
                                {
                                    ApplicationManager.PublicAtMessagePushForApplication(message);
                                    foreach (var socket in WebSocket.WebSocketAPI.WebSocketServerAPI.clientList)
                                    {
                                        socket.Send(message);
                                    }

                                });
                                break;

                            case "MESSAGE_AUDIT_PASS"://消息审核事件
                                Console.WriteLine(message);
                                break;

                            case "MESSAGE_AUDIT_REJECT"://消息审核不通过事件
                                Console.WriteLine(message);
                                break;
                            //--------------------------私信消息事件------------------------------
                            case "DIRECT_MESSAGE_CREATE"://用户通过私信发消息给机器人时
                                Task.Run(async () =>
                                {
                                    ApplicationManager.DirectMessagePushForApplication(message);
                                    foreach (var socket in WebSocket.WebSocketAPI.WebSocketServerAPI.clientList)
                                    {
                                        socket.Send(message);
                                    }
                                });
                                break;
                            case "DIRECT_MESSAGE_DELETE":// 删除（撤回）消息事件
                                Console.WriteLine(message);
                                break;
                            //--------------------------表情表态事件------------------------------
                            case "MESSAGE_REACTION_ADD"://用户对消息进行表情表态时
                                Task.Run(async () =>
                                {
                                    ApplicationManager.MessageReactionPushForApplication("MESSAGE_REACTION_ADD",message);
                                    foreach (var socket in WebSocket.WebSocketAPI.WebSocketServerAPI.clientList)
                                    {
                                        socket.Send(message);
                                    }
                                });
                                break;
                            //--------------------------互动事件------------------------------
                            case "INTERACTION_CREATE":
                                Task.Run(async () =>
                                {
                                    ApplicationManager.InteractionPushForApplication( message);
                                    foreach (var socket in WebSocket.WebSocketAPI.WebSocketServerAPI.clientList)
                                    {
                                        socket.Send(message);
                                    }
                                });
                                break;
                            case "MESSAGE_REACTION_REMOVE"://用户对消息进行取消表情表态时
                                Task.Run(async () =>
                                {
                                    ApplicationManager.MessageReactionPushForApplication("MESSAGE_REACTION_REMOVE", message);
                                    foreach (var socket in WebSocket.WebSocketAPI.WebSocketServerAPI.clientList)
                                    {
                                        socket.Send(message);
                                    }
                                });
                                break;
                            //--------------------------论坛事件，仅 *私域* 机器人能够设置此 intents。------------------------------
                            case "FORUM_THREAD_CREATE":// 当用户创建主题时
                                Console.WriteLine(message);
                                break;
                            case "FORUM_THREAD_UPDATE":// 当用户更新主题时
                                Console.WriteLine(message);
                                Console.WriteLine("用户更新主题");
                                break;
                            case "FORUM_THREAD_DELETE":// 当用户删除主题时
                                Console.WriteLine(message);
                                break;
                            case "FORUM_POST_CREATE":// 当用户创建帖子时
                                Console.WriteLine(message);
                                break;
                            case "FORUM_POST_DELETE":// 当用户删除帖子时
                                Console.WriteLine(message);
                                break;
                            case "FORUM_REPLY_CREATE":// 当用户回复评论时
                                Console.WriteLine(message);
                                break;
                            case "FORUM_REPLY_DELETE":// 当用户回复评论时
                                Console.WriteLine(message);
                                break;
                            case "FORUM_PUBLISH_AUDIT_RESULT":// 当用户发表审核通过时
                                Console.WriteLine(message);
                                break;
                            //--------------------------音频事件------------------------------
                            case "AUDIO_START"://音频开始播放时
                                break;

                            case "AUDIO_FINISH"://音频开始结束时
                                break;

                            case "AUDIO_ON_MIC"://机器人上麦时
                                break;

                            case "AUDIO_OFF_MIC"://机器人下麦时
                                break;
                        }
                        break;

                    case 7://服务端通知客户端重新连接
                        Reconnect();
                        break;

                    case 9://当identify或resume的时候，如果参数有错，服务端会返回该消息
                        Log.Log.LogErr("Bot鉴权", "机器人鉴权失败，请检查BotId和token，或检查config.json订阅事件");
                        Environment.Exit(0);
                        break;
                            
                    case 10: //当客户端与网关建立ws连接之后，网关下发的第一条消息
                        if (session_id != null)
                        {
                            Resume(BotId, Token, session_id, seq);
                            return;
                        }
                        LogSuc("Server", "已收到Hello包,正在发送鉴权信息");
                        heartbeat_interval = int.Parse(json.RootElement.GetProperty("d").GetProperty("heartbeat_interval").ToString());
                        LogSuc("Server", "心跳间隔为:" + heartbeat_interval);
                        SendMsg(SiriusClient, CreateAuthPack(BotId, Token, intents));
                        Sirius.Utils.Util.HeartartBeat_Timer=new System.Timers.Timer(Sirius.WebSocket.MessageManager.MessagePush.heartbeat_interval);
                        break;
                    case 11://当发送心跳成功之后，就会收到该消息
                        Sirius.Utils.Util.HeartBeat_Data = message;
                        break;
                    case 12://仅用于 http 回调模式的回包，代表机器人收到了平台推送的数据
                        break;
                    default:
                        LogWar("Server", "Sirius无法解析数据，请将框架升级至最新版本,以免影响使用...");
                        break;

                }
            }
            catch (Exception e)
            {
                LogWar("Server", "数据解析异常！" + e.Message);
            }
        }
    }
}
